package com.my.vertx.tcp;

import io.netty.handler.logging.ByteBufFormat;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;

/**
 * 使用vertx创建TCP客户端
 * <p>
 * <a href="https://vertx.io/docs/vertx-core/java/#_creating_a_tcp_client">Creating a TCP client</a>
 * </p>
 *
 * @author: marshal
 * @date: 2023-04-17 11:50
 */
public class VertxTcpClientTest {
    public static void main(String[] args) {
        // 创建vertx 对象
        Vertx vertx = Vertx.vertx();
        // 设置启动参数
        NetClientOptions options = new NetClientOptions()
                .setLogActivity(true)
                .setActivityLogDataFormat(ByteBufFormat.SIMPLE)
                .setConnectTimeout(10000)
                .setReconnectAttempts(10)
                .setReconnectInterval(500);
        // 创建TCP Client 对象
        NetClient client = vertx.createNetClient(options);
        // 创建连接
        client
                .connect(9800, "127.0.0.1")
                .onComplete(ar -> {
                    if (ar.succeeded()) {
                        System.out.println("Connected!");
                        // 拿到socket
                        NetSocket socket = ar.result();
                        // 写入数据到Server
                        socket.write("This is client!", "UTF-8");
                        // socket处理
                        socket.handler(buffer -> {
                            System.out.println("receive data  from server :" + buffer); 
                        });
                    } else {
                        System.out.println("Failed to connect: " + ar.cause().getMessage());
                    }
                });



    }
}
